package com.manlost.web.common;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.BeanUtils;

import com.manlost.biz.baby.model.dataobject.Baby;
import com.manlost.biz.baby.model.dataobject.BabyDraft;

public class BeanCopyUtils{
	private static final Log log = LogFactory.getLog(BeanCopyUtils.class);

	public static <V,T> T copyBean(V source, Class<T> clazz) {
		T target = null;
		try {
			target = clazz.newInstance();
		} catch (InstantiationException e) {
			log.error("copy Bean occurs errror!", e);
		} catch (IllegalAccessException e) {
			log.error("copy Bean occurs errror!", e);
		}
		BeanUtils.copyProperties(source, target);
		return target;
	}
	
	public static <V,T> List<T> copyList(List<V> list, Class<T> clazz) {
		List<T> targets=null;
		if(list==null){
			return Collections.<T>emptyList();
		}
		targets=new ArrayList<T>(list.size());
		for(Object source:list){
			T target = null;
			try {
				target = clazz.newInstance();
			} catch (InstantiationException e) {
				log.error("copy Bean List occurs errror!", e);
			} catch (IllegalAccessException e) {
				log.error("copy Bean List occurs errror!", e);
			}
			BeanUtils.copyProperties(source, target);
			targets.add(target);
		}
		return targets;
	}
	
	public static void main(String[] args) {
		BabyDraft draft=new BabyDraft();
		draft.setId(new Long(1));
		draft.setBabySource("ddd");
		Baby baby=BeanCopyUtils.copyBean(draft,Baby.class);
		System.out.println(baby.getId()+baby.getBabySource());
		List<BabyDraft> drafts=new ArrayList<BabyDraft>();
		drafts.add(draft);
		BabyDraft draft2=new BabyDraft();
		draft2.setId(new Long(2));
		draft2.setBabySource("ccc");
		drafts.add(draft2);
		List<Baby>babies=BeanCopyUtils.copyList(drafts,Baby.class);
		for(Baby baby2:babies){
			System.out.println(baby2.getId()+baby2.getBabySource());
		}
	}
}
